<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               :page="page"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <!--<template slot="menuLeft">-->
        <!--<el-button type="warning"-->
                   <!--size="small"-->
                   <!--plain-->
                   <!--icon="el-icon-download"-->
                   <!--@click="handleExport">导出-->
        <!--</el-button>-->
      <!--</template>-->
      <template slot-scope="{row}"
                slot="deptId">
        <el-tag>{{row.deptName}}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="siteId">
        {{row.siteName}}
      </template>
      <template slot-scope="{row}"
                slot="result">
        <el-tag  type="success" v-if="+row.result === 1">合格</el-tag>
        <el-tag  type="danger" v-else-if="+row.result === 2">不合格</el-tag>
        <el-tag   type="info" v-else>无数据</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {
    getList,
    getUser,
    remove,
    update,
    add,
    grant,
    resetPassword
  } from "@/api/onsite/feedingrecord";
  import {getDeptTree} from "@/api/system/dept";
  import {getRoleTree} from "@/api/system/role";
  import {getPostList} from "@/api/system/post";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import {getToken} from '@/util/auth';

  export default {
    data() {
      return {
        form: {},
        roleBox: false,
        excelBox: false,
        loading: true,
        selectionList: [],
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        init: {
          roleTree: [],
          deptTree: [],
        },
        props: {
          label: "title",
          value: "key"
        },
        roleGrantList: [],
        roleTreeObj: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          selection: true,
          delBtn: false,
          addBtn: false,
          viewBtn: true,
          dialogCloseBtn: true,
          columnBtn: true,
          editBtn: false,
          menu: true,
          menuWidth: 80,
          column: [
            {
              label: "所属组织",
              prop: "deptId",
              type: "select",
              search: false,
              dicUrl: "/api/blade-system/dept/tree",
              props: {
                label: "title",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属组织",
                trigger: "blur"
              }],
              span: 12,
              slot:true,
              cascaderChange: true,
              cascaderItem: ['siteId'],
              viewDisplay: false,
            },
            {
              label: "负责站点",
              prop: "siteId",
              search: false,
              selection:true,
              type: "tree",
              multiple: true,
              dicFlag: false,
              defaultIndex: 1,
              dicUrl: "/api/blade-system/site/select?deptId={{key}}",
              props: {
                label: "siteName",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择负责站点",
                trigger: "click"
              }],
              slot:true,
              span: 12,
              viewDisplay: false,
            },
            {
              label: "设备编号",
              prop: "deviceCode",
              search: true,
              viewDisplay: false,
            },
            {
              label: "设备型号",
              prop: "deviceName",
              search: true,
              viewDisplay: false,
            },
            {
              label: "入料时间",
              prop: "feedingTime",
              search: false,
            },
            {
              label: "环境平均温度",
              prop: "averageAmbientTemperature",
              search: false,
              hide:true,
            },
            {
              label: "菌剂投放量",
              prop: "dosageBacteria",
              search: false,
              hide:true,
            },
            {
              label: "辅料添加",
              prop: "accessoriesAddition",
              search: false,
              hide:true,
            },
            {
              label: "物料温度设置一阶段",
              prop: "materialTemperatureSetting1",
              search: false,
              hide:true,
            },
            {
              label: "物料温度设置二阶段",
              prop: "materialTemperatureSetting2",
              search: false,
              hide:true,
            },
            {
              label: "物料温度设置三阶段",
              prop: "materialTemperatureSetting3",
              search: false,
              hide:true,
            },
            {
              label: "仓内湿度设置一阶段",
              prop: "warehouseHumiditySetting1",
              search: false,
              hide:true,
            },
            {
              label: "仓内湿度设置二阶段",
              prop: "warehouseHumiditySetting2",
              search: false,
              hide:true,
            },
            {
              label: "仓内湿度设置三阶段",
              prop: "warehouseHumiditySetting3",
              search: false,
              hide:true,
            },
            {
              label: "含氧量设置",
              prop: "oxygenContentSetting",
              search: false,
              hide:true,
            },
            {
              label: "搅拌设置",
              prop: "mixingSetting",
              search: false,
              hide:true,
            },
            {
              label: "入料重量(g)",
              prop: "feedWeight",
              search: false,
            },
            {
              label: "入料间隔",
              prop: "feedingInterval",
              search: false,
              hide:true,
            },
            {
              label: "操作员",
              prop: "operatorPerson",
              search: false,
              viewDisplay: false,
            },
            {
              label: "开始时间",
              type: "datetime",
              prop: "startTime",
              search: true,
              hide:true,
              span:16,
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              viewDisplay: false,
            },
            {
              label: "结束时间",
              type: "datetime",
              prop: "endTime",
              search: true,
              hide:true,
              span:16,
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              viewDisplay: false,
            },
          ]
        },
        data: [],
        searchForm: {},
        searchFormChatFalg: true
      };
    },
    watch: {
      'form.tenantId'() {
        if (this.form.tenantId !== '') {
          getDeptTree(this.form.tenantId).then(res => {
            const column = this.findObject(this.option.column, "deptId");
            column.dicData = res.data;
          });
          getRoleTree(this.form.tenantId).then(res => {
            const column = this.findObject(this.option.column, "roleId");
            column.dicData = res.data;
          });
//          getPostList(this.form.tenantId).then(res => {
//            const column = this.findObject(this.option.column, "siteId");
//            column.dicData = res.data;
//          });
        }
      },
    },
    computed: {
      ...mapGetters(["userInfo", "permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.user_add, false),
          viewBtn: this.vaildData(this.permission.user_view, false),
          delBtn: this.vaildData(this.permission.user_delete, false),
          editBtn: this.vaildData(this.permission.user_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    methods: {
      submitRole() {
        const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
        grant(this.ids, roleList).then(() => {
          this.roleBox = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.onLoad(this.page);
        });
      },
      rowSave(row, done, loading) {
        //新增用户
        if (Array.isArray(row.roleId)) {
          row.roleId = row.roleId.join(",");
        }
        if (Array.isArray(row.siteId)) {
          row.siteId = row.siteId.join(",");
        }
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
//        row.deptId = row.deptId.join(",");
        console.log(row);
          if (Array.isArray(row.roleId)) {
            row.roleId = row.roleId.join(",");
          }
         if (Array.isArray(row.siteId)) {
           row.siteId = row.siteId.join(",");
         }


        update(row).then(() => {
          done&&done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading&&loading();
        });
      },
      statusUpdate(row, index, done, loading) {
        row.status = !!row.status ? 0 :1
        update(row).then(() => {
          done&&done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading&&loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleReset() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择账号密码重置为123456?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return resetPassword(this.ids);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleGrant() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.roleTreeObj = [];
        if (this.selectionList.length === 1) {
          this.roleTreeObj = this.selectionList[0].roleId.split(",");
        }
        getRoleTree().then(res => {
          this.roleGrantList = res.data.data;
          this.roleBox = true;
        });
      },
      handleImport() {
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        done();
        this.excelBox = false;
        this.refreshChange();
      },
      handleTemplate() {
        window.open(`/api/blade-user/export-template?blade-auth=${getToken()}`);
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getUser(this.form.id).then(res => {
            this.form = res.data;
//            console.log(this.form);
//            if(this.form.hasOwnProperty("deptId")){
//              this.form.deptId = this.form.deptId.split(",");
//            }
//            if(this.form.hasOwnProperty("roleId")){
//              this.form.roleId = this.form.roleId.split(",");
//            }
//            if(this.form.hasOwnProperty("siteId")){
//              this.form.siteId = this.form.siteId.split(",");
//            }
          });
        }
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        try{
          this.searchForm = (this.$refs.crud || {}).searchForm || {};
          this.searchFormChatFalg = !this.searchFormChatFalg
        } catch  (e) {

        }

        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
        });
        getDeptTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "deptId");
          column.dicData = res.data;
        });
      }
    }
  };
</script>

<style>
    /*.el-form-item__label{*/
      /*!*white-space: nowrap;*!*/
      /*width: 100px !important;*/
    /*}*/
  /*.el-form-item__content{*/
    /*margin-left: 100px !important;*/
  /*}*/
</style>
